/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "modulehandler.h"

#include <machine/machine.h>
#include <kerneldebugconsole.h>
#include <bootstrapinfo.h>
#include <stdlib.h>

ModuleHandler::ModuleHandler() {
}

void ModuleHandler::init() {
    Multiboot_info *minfo = PLMachine::instance().multibootInfo();
	uint32_t i;
	Multiboot_moduleList *modEntry;
    PLKernelDebugConsole::instance().printf("\nLoading module information ... ");
	for (i = 0, modEntry = (Multiboot_moduleList *)minfo->mods_addr ; i < minfo->mods_count ; i++, modEntry++) {
		PLKernelDebugConsole::instance().printf("\n  Module: 0x%x 0x%x 0x%x %s", modEntry->mod_start, modEntry->mod_end, modEntry->mod_cmdline, modEntry->mod_cmdline);
        m_modules.insert(getModuleName(const_cast<const char *>(reinterpret_cast<char *>(modEntry->mod_cmdline))),
                         new ModuleInfo(modEntry->mod_start, modEntry->mod_end, reinterpret_cast<char *>(modEntry->mod_cmdline)));
	}
    PLKernelDebugConsole::instance().printf("\ndone");
}

const char *ModuleHandler::getModuleName(const char *commandline) {
    int len = strlen(commandline);
    int i;
    for(i = 0 ; i < len ; i++) {
        if(commandline[i] == ' ') {
            break;
        }
    }
    if(i < len) {
        void *d = malloc(i);
        char *ret = reinterpret_cast<char *>(d);
        memcpy(ret, commandline, i);
        return ret;
    }
    return commandline;
}

const ModuleInfo *ModuleHandler::getModuleInfo(const char *moduleName) {
    return m_modules.lookup(moduleName);
}
